Using modules

Python has a great variety of modules that can be used for differente tasks. For instance, there are modules to read/write Excel files, processing large amounts of data, manipulating astronomical coordinates or making plots.

There are at least three options to use modules in Python.

Using import

The first option to use a module is with the command import followed by the module name.

import math

Whenever we want to use a function from that module we have to do it by writing the libraty name followed by a dot (.) and the function. If you write math. and use the Tab key, that should show a list with the functions that are part of the module.


In [ ]:
import math

In [ ]:
math.

In [ ]:
# we can use now some function
math.sin(math.pi/2)

Using from

Another option is importing only the function that you need

from math import sin

In this case only the function sin is imported and not the rest of the library


In [ ]:
from math import sin

In [ ]:
sin(1.0)

However, you cannot use pi because it has not been imported


In [ ]:
sin(pi/2)

you could import it in the same way as we did with sin


In [ ]:
from math import sin, pi # now pi is available

In [ ]:
sin(pi/2)

Using import as

You can also rename a module at the moment of importing it.

import math as mt

In this case, instead of using math.sin() we can use mt.sin()


In [ ]:
import math as mt

You can then use the following to see the documentation of a function


In [ ]:
mt.sin?

Exercise 4.1

Import the module random and use the function shuffle to shuffle the contents of a list that has the integers from 0 to 9. Print the list before and after shuffling. Use random.shuffle? to read the documentation string for that function.


In [ ]:
import random

In [ ]: